package com.bilibili.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bilibili.entity.CommonResult;
import com.bilibili.entity.Follow;
import com.bilibili.entity.User;
import com.bilibili.service.FollowService;
import com.bilibili.service.UserService;
import com.bilibili.service.impl.FollowServiceImpl;
import com.bilibili.service.impl.UserServiceImpl;

@SuppressWarnings("serial")
@WebServlet("/clickAttention")
public class ClickAttentionServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json; charset=utf-8");
		int followeeId = ((User)request.getSession().getAttribute("loginUser")).getUserId();
		String videoId = request.getParameter("videoId");
		int upId = -1;
		try {
			upId = Integer.parseInt(videoId);
		} catch (Exception e) {
			// TODO: handle exception
		}
		UserService us= new UserServiceImpl();
		User u = us.selectUpAllInfo(upId);
		int followerId = u.getUserId();
		Follow f = new Follow();
		f.setFollowerId(followerId);
		f.setFolloweeId(followeeId);
		FollowService fs = new FollowServiceImpl();
		CommonResult cr = new CommonResult();
		if(fs.selectUserIsFollower(f) == null) {
			if(request.getParameter("action").equals("add")) {
				if(fs.insertMyAttention(f)) {
					cr.setCode(200);
				}else {
					cr.setCode(409);
				}
			}
		}else {
			if(request.getParameter("action").equals("remove")){
				if(fs.deleteMyAttention(f)) {
					cr.setCode(200);
				}else {
					cr.setCode(409);
				}
			}
		}
		response.getWriter().write(cr.toJSONString());
	}
}
